package com.my.demo.shiro;

import com.my.demo.shiro.realms.CustomerRealm;
import java.util.HashMap;
import java.util.Map;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author liangyuanshao
 * @date 2021/12/18 - 18:40
 */
@Configuration
public class ShiroConfig {
  @Bean
  public ShiroFilterFactoryBean getShiroFilterFactoryBean(
      DefaultWebSecurityManager defaultWebSecurityManager){

    ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
    //给filter设置安全管理器
    shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

    //配置系统受限资源
    //配置系统公共资源
    Map<String,String> map = new HashMap<String,String>();
    map.put("/login","anon");//anon 设置为公共资源  放行资源放在下面
    map.put("/sendSms","anon");
    map.put("/register","anon");
    map.put("/changePassword","anon");
    map.put("/updatePassword","anon");

    //测试
//    map.put("/uploadHead","anon");
//    map.put("/upload","anon");

    map.put("/**","authc");//authc 请求这个资源需要认证和授权

    //默认认证界面路径---当认证不通过时跳转
    shiroFilterFactoryBean.setLoginUrl("/redirect.html");
    shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

    return shiroFilterFactoryBean;
  }

  //2.创建安全管理器
  @Bean
  public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm){
    DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
    //给安全管理器设置
    defaultWebSecurityManager.setRealm(realm);

    return defaultWebSecurityManager;
  }

  //3.创建自定义realm
  @Bean
  public Realm getRealm(){
    CustomerRealm customerRealm = new CustomerRealm();
    //设置hashed凭证匹配器
    HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
    //设置md5加密
    credentialsMatcher.setHashAlgorithmName("md5");
    //设置散列次数
    credentialsMatcher.setHashIterations(1024);
    customerRealm.setCredentialsMatcher(credentialsMatcher);
    return customerRealm;
  }


}
